package com.fr.chicken.controller;

import com.fr.chicken.dao.ActivationLogDao;
import com.fr.chicken.dao.GoodsLogDao;
import com.fr.chicken.dao.RechargeLogDao;
import com.fr.chicken.manager.activation.ActivationManager;
import com.fr.chicken.model.ActivationLog;
import com.fr.chicken.model.GoodsLog;
import com.fr.chicken.model.RechargeLog;
import com.fr.chicken.pay.com.shb.pay.main.PayConfig;
import com.fr.chicken.pay.com.shb.pay.util.RSAUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping(value = "/api/notify")
public class NotifyController {

    @Autowired
    private RechargeLogDao rechargeLogDao;

    @Autowired
    private ActivationManager activationManager;

    @Autowired
    private GoodsLogDao goodsLogDao;
    /**
     * notify 回执成功
     */
    public static String NOTIFY_SUCCESS = "SUC";
    /**
     * notify 回执失败
     */
    public static String NOTIFY_FAIL = "FAIL";


    @RequestMapping(value = "/shb", method = {RequestMethod.POST})
    public String shbNotify(@RequestBody String json) {
//        json = "{\"message\":{\"code\":200,\"content\":\"成功\"},\"context\":\"GRBRRZPI+m6PZ5cZylGXEOin5b4Qp9OwuysI8kEIp1YQ/pn6uS/j4eHn0Hc+TXHHDkXX5IX2+BQHcdamc/FjAbVlXh1PBgQ9OjDVC89qV4I1KWCeni+4tMmsio6MT9kNr1FOkbuByM/wdPdFvWzBtTAZD9gNm5rV2oCoqVFckR0y+wSsbir+m9UPVsd+vK3meuPbSRE+QDWf9pCGotUJ5zJPWR8copmU9ebhnl2EHF1lGFCxLEcHRTDyWEz/G4qT2R4AauLrF3CYgxBFUltflh30csU5EqSAsoqoBaFcty37wj6e6xGbujhTEWORcU1GEPdaZSNsIpkBRj2lr9IWxYjoJJoj7zccQPLlfrx6bmE8+zmZAphg8KFMj4ifd7lj13amIjz5Y6+YiOUfSyt3igPuJ9evsstrww5qa66i2g6tBhsRt5Y02A7cgLvspA/1Ka7QIUS0pZEYUAniVjb2ii5+j0f7W6CQKO4/CGKOacyF6tWmooeowL8fe/13q6SDf6q+SoSY/S8tFXQbPGl03mghFa2XVS310flauxe56bmI7XPqPOYdI0KSaureflk4t8dys/W7NKvDKEANNx+PZX32bqlI6ZNuRkhFISJDRDD1efQl9rSJI9IjSzIWLDLVk2Z0P2sdJ2l3YKxbFiDWyB6OG64wT5/RdM93qGOLaeldyniZtyj0y8Yo5GLU6oBMer93MoL8S0t5GvnN1mjWovRCPSUbeURjOpyY8674XGTe47gp/4wzMdOq0M4menzFKVmDu1qfnp1zmrUkQsJsHa6Af2BzYwzyRigaTKV4fOVp9fMFXXXuMXQfizlkow1Q/FyYU+4VRWF7V4vq7LJx92uEELcTB7qQNG9Pw0ZpBf0m0d77vpZDhm8qhE4w9vAxoLHGUw4eCnHhw3AujgSbM8tak9wu+mQO/nMSAKyMxuns8rsRqcP85kvqNFR2Vn7W6WJm57X1CDjw9YRB6DeMPE6pTN0BlDabcKvu2invBLuKFa2/ZMafn2z3gckF6giN\",\"success\":true}";
        try {
            System.err.println("shb异步通知报文,json:{"+json+"} ");
            JSONObject requestJson = JSONObject.fromObject(json);
            String decrypt = RSAUtils.decryptByPrivateKey(requestJson.getString("context"), PayConfig.MCH_PRIVATE_KEY);
            JSONObject jsonObject = JSONObject.fromObject(decrypt);

            JSONObject head = jsonObject.getJSONObject("businessHead");
            System.err.println("shb异步通知报文,解密后,head:"+head+" ");
            JSONObject context = jsonObject.getJSONObject("businessContext");
            System.err.println("shb异步通知报文,解密后,context:{"+context+"} " );

            if (!RSAUtils.verify(jsonObject.toString(),PayConfig.SHB_PUBLIC_KEY)){
                throw new Exception("验签错误");
            }
            if (!"SUC".equals(context.getString("orderStatus"))){
                return NOTIFY_FAIL;
            }
            //调用统一订单完成处理器
            String merchantOrderNumber = context.get("merchantOrderNumber") == null ? "" : context.getString("merchantOrderNumber");
            String shbOrderNumber = context.get("shbOrderNumber") == null ? "" : context.getString("shbOrderNumber");
            String merchantNumber = context.get("merchantNumber") == null ? "" : context.getString("merchantNumber");
            String orderStatus = context.get("orderStatus") == null ? "" : context.getString("orderStatus");
            String defrayalType = context.get("defrayalType") == null ? "" : context.getString("defrayalType");
            String currenciesType = context.get("currenciesType") == null ? "" : context.getString("currenciesType");
            String totalAmount = context.get("totalAmount") == null ? "" : context.getString("totalAmount");//分
            String fee = context.get("fee") == null ? "" : context.getString("fee");//分
            String payBank = context.get("payBank") == null ? "" : context.getString("payBank");
            String paymentTime = context.get("paymentTime") == null ? "" : context.getString("paymentTime");
           System.out.println("支付回调成功："+shbOrderNumber);
            if(StringUtils.isNotBlank(shbOrderNumber)) {
                synchronized (shbOrderNumber.intern()) {
                    RechargeLog log = rechargeLogDao.selectRechargeLogByOrderNum(shbOrderNumber);
                    if (log != null && log.getStat() == 1) {// 待处理的订单
                        GoodsLog goodsLog = new GoodsLog();
                        goodsLog.setGoodsId(log.getGoodsId());
                        goodsLog.setPlayerId(log.getPlayerId());
                        goodsLog.setTime(new Date().getTime());
                        goodsLog.setInfo(activationManager.generateActivation());
                        System.out.println("添加商品：" + log.getPlayerId());
                        int insetNum = goodsLogDao.insertSelective(goodsLog);
                        if (insetNum > 0) {
                            System.out.println("插入条数" + insetNum);
                            log.setStat(2);
                            if (rechargeLogDao.updateByPrimaryKey(log) > 0) {
                                System.out.println("更新订单状态：" + log.getStat());
                            } else {
                                System.out.println("更新订单状态失败：" + log.getId() + "---" + log.getStat());
                            }

                        }
                    } else {
                        System.out.println("订单未找到，或者已经处理了");
                    }
                }
            }
            return NOTIFY_SUCCESS;
        }catch (Exception e) {
            e.printStackTrace();
            return NOTIFY_FAIL;
        }
    }
}
